import { getIslandMaterialBooks, getProjectManagerMemberListResult, getProjectRoleInformation, getBusinessTypeList, deleteIslandMaterialBook, getIslandPdfByCategory, IslandIntoMaterialBook } from '../../../../../api/index'

Component({
  properties: {
    detail: {
      type: Object,
      value: {}
    },
    roleIds: {
      type: Array,
      value: []
    }
  },
  data: {
    business: [],
    activeBusiness: '',
    businessTitle: '',
    memberBusiness: '',
    materialBusiness: '',
    paperBusiness: '',
    roleInformation: {},
    memberList: [],
    activeMember: '',
    memberTitle: '',
    currentMember: {},
    activeCate: 0,
    refresher: false,
    categorys: [
      { label: '全部空间', value: 0, key: 'allCount', allCount: 0 },
      { label: '主材表', value: 1, key: 'mainCount', mainCount: 0 },
      { label: '洁具表', value: 2, key: 'sanitaryCount', sanitaryCount: 0 },
      { label: '五金表', value: 3, key: 'hardwareCount', hardwareCount: 0 },
      { label: '开关面板表', value: 4, key: 'buttonCount', buttonCount: 0 },
      { label: '电器', value: 5, key: 'electricalCount', electricalCount: 0 },
      { label: '灯具', value: 6, key: 'lightingCount', lightingCount: 0 }
    ],
    sections: []
  },
  methods: {
    async onRefresh () {
      await this.getBusiness()
      this.setData({ refresher: false })
    },
    async download ({ currentTarget: { dataset: { item } } }) {
      try {
        const { ResultSet } = await getIslandPdfByCategory({ bookNo: item.bookNo, category: this.data.activeCate })
        const { errMsg } = await wx.$pro.setClipboardData({ data: ResultSet.userData.fileUrl })
        if (errMsg === 'setClipboardData:ok') {
          wx.showToast({ title: 'PDF文件地址已复制，请到浏览器中下载并查看！', icon: 'none' })
        }
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async delBook () {
      try {
        if (!this.data.sections.length) {
          wx.showToast({ title: '请先选择要删除的数据！', icon: 'none' })
          return
        }
        const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除选择的材料册吗？' })
        if (confirm) {
          let ids = this.data.sections.map(item => { return item.bookNo })
          await deleteIslandMaterialBook({ projectId: this.data.detail.project_id, bookNos: ids, roleIds: this.data.roleIds })
          wx.showToast({ title: '删除成功！', icon: 'none' })
          this.getList()
        }
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    selectCate ({ currentTarget: { dataset: { item } } }) {
      this.setData({ activeCate: item.value })
      this.getList()
    },
    // selectMember ({ currentTarget: { dataset: { item } } }) {
    //   this.selectComponent('#member').toggle()
    //   this.setData({ activeMember: item.userId, memberTitle: item.userName })
    //   this.getList()
    // },
    selectMember ({ currentTarget: { dataset: { item } } }) {
      this.selectComponent('#member').toggle()
      this.setData({ activeMember: item.userId, memberTitle: item.userName, activeSpace: '', currentMember: item })
      this.getList()
      // this.getSpaceList()
    },
    selectBusiness ({ currentTarget: { dataset: { item } } }) {
      this.selectComponent('#business').toggle()
      this.setData({ activeBusiness: item.id, businessTitle: item.title, activeMember: '', memberTitle: '全部成员' })
      this.getMemberList()
      this.getList()
    },
    async confirmJoin () {
      try {
        if (this.locking) return
        this.locking = true
        let bookNos = this.data.sections.map(item => { return item.bookNo })
        await IslandIntoMaterialBook({ bookNos: bookNos, projectId: this.data.detail.project_id, roleIds: this.data.roleIds })
        wx.showToast({ title: '入册成功！', icon: 'none' })
        await this.getList()
        this.locking = false
      } catch (err) {
        this.locking = false
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    cancelAll () {
      this.data.bookList.forEach(item => {
        item.isChecked = false
      })
      this.setData({ bookList: this.data.bookList, sections: [] })
    },
    selectBookRadio ({ currentTarget: { dataset: { item, index } } }) {
      let key = `bookList[${index}].isChecked`
      this.setData({ [key]: !item.isChecked })
      let sections = this.data.bookList.filter(item => item.isChecked)
      this.setData({ sections: sections })
    },
    setBusiness () {
      let business = this.data.detail.business_type.split(',')
      let newBusiness = []
      this.data.businessList.forEach(item => {
        business.forEach(row => {
          if (item.id === parseInt(row)) newBusiness.push(item)
        })
      })
      this.setData({
        business: newBusiness,
        activeBusiness: newBusiness[0].id,
        businessTitle: newBusiness[0].title,
        memberBusiness: newBusiness[0].id,
        materialBusiness: newBusiness[0].id,
        paperBusiness: newBusiness[0].id
      })
    },
    async getBusiness () {
      try {
        const { ResultSet } = await getBusinessTypeList()
        this.setData({ businessList: ResultSet.userData.businessList.value })
        this.setBusiness()
        this.getProjectRoleInformation()
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getMemberList () {
      try {
        const { ResultSet } = await getProjectManagerMemberListResult({ project_id: this.data.detail.project_id, business_type: this.data.activeBusiness, isMaterialManager: this.data.roleInformation.materialManager })
        let activeItem = ResultSet.userData.memberList[0]
        this.data.activeMember = activeItem.userId
        this.data.memberTitle = activeItem.userName
        this.setData({ memberList: ResultSet.userData.memberList, activeMember: this.data.activeMember, memberTitle: this.data.memberTitle, currentMember: activeItem })
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getProjectRoleInformation () {
      try {
        const { ResultSet } = await getProjectRoleInformation({ projectId: this.data.detail.project_id, roleIds: this.data.roleIds, businessType: this.data.activeBusiness })
        this.setData({ roleInformation: ResultSet.userData })
        this.getMemberList()
        this.getList()
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getList () {
      try {
        let query = {
          category: this.data.activeCate,
          businessType: this.data.activeBusiness,
          projectId: this.data.detail.project_id,
          roleIds: this.data.roleIds
        }
        if (this.data.activeMember) query.userId = this.data.activeMember
        const { ResultSet } = await getIslandMaterialBooks({ ...query })
        ResultSet.userData.materialBooks.forEach(item => {
          item.isChecked = false
        })
        this.data.categorys.forEach(item => {
          item[item.key] = ResultSet.userData[item.key]
        })
        this.setData({ bookList: ResultSet.userData.materialBooks, categorys: this.data.categorys })
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    }
  },
  created () {
    this.getBusiness()
  }
})